package com.iyunwen.datatool.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

/**
 * @description: 文件处理方法
 * @author: Zhu.Guodong
 * @create: 2020-03-19 09:48
 * @version:
 */
public class FileUtils {


    /**
     * 获取文件编码
     * @param file
     * @return
     * @throws IOException
     */
    public static String getFileCharsetName(File file) throws IOException {

        InputStream inputStream = new FileInputStream(file);

        byte[] head = new byte[3];

        inputStream.read(head);

        //或GB2312，即ANSI
        String charsetName = "GBK";

        if (head[0] == -1 && head[1] == -2) {
            //0xFFFE
            charsetName = "UTF-16";
        } else if (head[0] == -2 && head[1] == -1) {
            //0xFEFF
            //包含两种编码格式：UCS2-Big-Endian和UCS2-Little-Endian
            charsetName = "Unicode";
        } else if (head[0] == -27 && head[1] == -101 && head[2] == -98) {
            //UTF-8(不含BOM)
            charsetName = "UTF-8";
        } else if (head[0] == -17 && head[1] == -69 && head[2] == -65) {
            //UTF-8-BOM
            charsetName = "UTF-8";
        }

        inputStream.close();
        return charsetName;

    }


    /**
     * 获取目录下的文件
     * @param path
     * @return
     */
    public static List<File> readFilesByPath(String path) {
        File fileDirection = new File(path);
        if (fileDirection.exists() && fileDirection.isDirectory()) {
            File[] files = fileDirection.listFiles();
            return Arrays.asList(files);
        }
        return null;
    }
}
